package com.quzi.kettle.activitise;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.quzi.kettle.R;
import com.quzi.kettle.socket.UdpReceive;
import com.quzi.kettle.socket.UdpSend;

public class UdpTest extends Activity {
	private Button send, receive;
	private EditText eText;
	private static TextView tView;

	// private static boolean flag = false;
	private static StringBuffer sb = new StringBuffer();
	private UdpReceive udpReceive = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_udp);

		send = (Button) findViewById(R.id.button_udp_send);
		send.setOnClickListener(clickListener);
		receive = (Button) findViewById(R.id.button_udp_receive);
		receive.setOnClickListener(clickListener);
		receive.setEnabled(true);

		eText = (EditText) findViewById(R.id.edittext_udp);
		tView = (TextView) findViewById(R.id.textview_udp);

	}

	private static Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1: {
				Bundle data = msg.getData();
				String result = data.getString("result");
				sb.append(result);
				tView.setText(sb);

				break;
			}
			case 0: {
				break;
			}
			}

		};
	};
	View.OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (v.getId() == R.id.button_udp_send) {
				new UdpSend(eText.getText().toString().getBytes());

			}
			if (v.getId() == R.id.button_udp_receive) {

				tView.setText("正在接收udp....");

				getUdpReceive().start();

			}

		}
	};

	private UdpReceive getUdpReceive() {

		// if (udpReceive == null) {
		// udpReceive = UdpReceive.getInstance(handler, true);
		// }
		// return udpReceive;
		udpReceive = null;
		udpReceive = new UdpReceive(handler, true);
		return udpReceive;
	}
}
